import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_advanced_drawer/flutter_advanced_drawer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sj001/pages/chatPage/chatPage.dart';
import 'package:sj001/pages/drawer/historyItem.dart';
import 'package:sj001/request/request.dart';
import 'package:get/get.dart';
import '../../model/historyConversionsModel.dart';

class HistoryPage extends StatefulWidget {
  HistoryPage( {required this.advancedDrawerController,Key? key}) : super(key: key);
  AdvancedDrawerController advancedDrawerController;

  @override
  State<HistoryPage> createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  List<HistoryConversionItem> list = <HistoryConversionItem>[];
  final RefreshController refreshController =
      RefreshController(initialRefresh: false);
  bool isRequesting = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    onRefresh();
  }

  onRefresh() {
    if (!isRequesting) {
      request('').then((value) {
        if (value != null) {
          list.clear();
          list.addAll(value.data ?? []);
        }
        refreshController.refreshCompleted(resetFooterState: true);
        setState(() {});
      });
    } else {
      refreshController.refreshCompleted(resetFooterState: true);
    }
  }

  onLoading() {
    if (!isRequesting) {
      request(list.lastOrNull?.id ?? '').then((value) {
        if (value != null) {
          list.addAll(value.data ?? []);
        }
        setState(() {});
        refreshController.loadComplete();
      });
    } else {
      refreshController.loadComplete();
    }
  }

  Future<HistoryConversionsModel?> request(String lastId) async {
    isRequesting = true;
    HistoryConversionsModel? model =
        await CustomRequest.historyConversations(lastId: lastId);
    isRequesting = false;
    return model;
  }

  onTap(HistoryConversionItem item) {
    widget.advancedDrawerController.toggleDrawer();
    Get.to(()=>ChatPage(
      conversation_id: item.id ?? '',
      showAppBar: true,
    ));
  }

  onDelete(HistoryConversionItem item) async {
    bool ret =
        await CustomRequest.deleteConversion(conversation_id: item.id ?? '');
    if (ret) {
      list.remove(item);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 100,
        elevation: 1,
        leading: Container(
          margin: const EdgeInsets.only(left: 15),
          alignment: Alignment.centerLeft,
          decoration: const BoxDecoration(color: Colors.transparent),
          child: const Text(
            '历史记录',
            style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.w600,
              fontSize: 18,
            ),
          ),
        ),
        actions: [
          InkWell(
            onTap: ()=>widget.advancedDrawerController.toggleDrawer(),
            child: const Icon(
              Icons.close_rounded,
              size: 30,
              color: Colors.black,
            ),
          )
        ],
      ),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus? mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = const Text("pull up load");
            } else if (mode == LoadStatus.loading) {
              body = const CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = const Text("Load Failed!Click retry!");
            } else if (mode == LoadStatus.canLoading) {
              body = const Text("release to load more");
            } else {
              body = const Text("No more Data");
            }
            return SizedBox(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: refreshController,
        onRefresh: onRefresh,
        onLoading: onLoading,
        child: ListView.builder(
          itemBuilder: (ctx, index) {
            HistoryConversionItem item = list[index];
            return HistoryItem(
              list[index],
              onTap: () => onTap(item),
              onDelete: onDelete,
            );
          },
          itemCount: list.length,
        ),
      ),
    );
  }
}
